package main

import (
	"fmt"
	"sync"
)

// producer 生产者
func producer(ch chan int) {
	defer wg.Done()
	defer close(ch) // 写入完毕后关闭
	for i := 0; i < 100; i++ {
		fmt.Println("producer ", i)
		ch <- i
	}
}

// consumer 消费者
func consumer(ch chan int) {
	defer wg.Done()
	for true {
		val, ok := <-ch
		if ok {
			// 没有关闭
			fmt.Println("consumer ", val)
		} else {
			break
		}
	}
}

// 计数器锁
var wg sync.WaitGroup

func main() {
	wg.Add(2)
	var ch = make(chan int, 100)
	go consumer(ch)
	go producer(ch)
	wg.Wait() // 阻塞等待
	fmt.Println("process end...")
}
